const db = require('../db/connMysql');

const mysql_tool = {
    // 创建事务
    mysqlTransation(connection) {
        return new Promise((resolve, reject) => {
            connection.beginTransaction(err => {
                if (err) {
                    connection.release();
                    reject({success: false, err});
                    return;
                }
                resolve({success: true, connection});
            });
        });
    },
    // 普通执行sql
    /*
     * closeConnection 参数 传入 true 时，失败与否都关闭链接
     * closeConnection 参数 不传入任何参数时，失败与否都不关闭链接
     */
    execSql(sql, data, closeConnection=true) {
        return new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    connection.release();
                    reject(err);
                    return ;
                }
                connection.query(sql, data, function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        if (closeConnection) connection.release();
                        reject(err);
                        return ;
                    }
                    if (closeConnection) connection.release();
                    resolve(result);
                });
            });
        });
    },
    // 在事务环境中执行sql
    execSqlInTransaction(connection, sql, data) {
        return new Promise((resolve, reject) => {
            connection.query(sql, data, function (err, result) {
                if (err) {
                    // 连上数据库之后，执行sql时发生错误，回滚
                    connection.rollback(() => {
                        connection.release();
                        reject({success: false, err});
                    });
                    return ;
                }
                resolve({success: true, result});
            });
        });
    },
    // 提交事务
    commitTransaction(connection) {
        return new Promise((resolve, reject) => {
            connection.commit((err) => {
                if (err) {
                    connection.rollback(() => {
                        connection.release();
                        reject(false);
                    });
                    return;
                }
                connection.release();
                resolve(true);
            });
        });
    },
    // 手动回滚事务
    rollbackTransaction(connection) {
        return new Promise((resolve, reject) => {
            connection.rollback(() => {
                connection.release();
                resolve(true);
            });
        });
    },
};


module.exports = mysql_tool;